package com.xiaoxin_project.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaoxin_project.Util.*;
import com.xiaoxin_project.enums.MsgActionEnum;
import com.xiaoxin_project.enums.MsgSignFlagEnum;
import com.xiaoxin_project.enums.SearchFriendsStatusEnum;
import com.xiaoxin_project.mapper.ChatMsgMapper;
import com.xiaoxin_project.mapper.FriendsRequestMapper;
import com.xiaoxin_project.mapper.MyFriendsMapper;
import com.xiaoxin_project.mapper.UserMapper;
import com.xiaoxin_project.netty.ChatMsg;
import com.xiaoxin_project.netty.DataContent;
import com.xiaoxin_project.netty.UserChannelRel;
import com.xiaoxin_project.pojo.FriendsRequest;
import com.xiaoxin_project.pojo.MyFriends;
import com.xiaoxin_project.pojo.Users;
import com.xiaoxin_project.pojo.vo.FriendsVo;
import com.xiaoxin_project.pojo.vo.MyFriendsVo;
import com.xiaoxin_project.service.UserService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.beanutils.Converter;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private Sid sid;

    @Autowired
    private QRCodeUtils qrCodeUtils;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private MyFriendsMapper myFriendsMapper;

    @Autowired
    private FriendsRequestMapper friendsRequestMapper;

    @Autowired
    private ChatMsgMapper chatMsgMapper;


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {
        QueryWrapper<Users> qw = new QueryWrapper<>();
        qw.eq("username", username);
        Users result = userMapper.selectOne(qw);
        return result != null ? true : false;

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username, String Pwd) {
        QueryWrapper<Users> wr = new QueryWrapper<>();
        wr.eq("username", username).eq("password", Pwd);
        Users users = userMapper.selectOne(wr);
        return users != null ? users : null;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users saveUser(Users users) throws Exception {
        String userId = sid.nextShort();
        //随机生成一个cid
        String Cid = sid.nextShort();
        //每个用户唯一的二维码
        String qrCodePath = "C://user" + userId + "qrcode.png";
        //xiaoxin_pcode:[username] 格式
        qrCodeUtils.createQRCode(qrCodePath,"xiaoxin_pcode:"+users.getUserName());
        MultipartFile qrcodeFile = FileUtils.fileToMultipart(qrCodePath);
        //返回的路径 往数据库里保存
        String qrCode = fastDFSClient.uploadQRCode(qrcodeFile);
        String Prcode = qrCode;

        users.setCids(Cid);
        users.setPrcode(Prcode);
        users.setId(userId);
        userMapper.insert(users);
        return users;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users updateUserInfo(Users users) {
        userMapper.updateById(users);
        return userMapper.selectById(users.getId());
    }

    /**
     * 查询用户信息（根据Id）
     */
    @Override
    public Users queryById(String userId) {
        return userMapper.selectById(userId);
    }

    /**
     *添加好友查询
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Integer precondttionSearchFriends(String myUserId, String friendUsername) {
        //1.用户不存在
        Users users = queryUserInfoByUsername(friendUsername);
        if (users == null) {
            return SearchFriendsStatusEnum.USER_NOT_EXIST.status;
        }
        //2.不能添加自己
        if (users.getId().equals(myUserId)) {
            return SearchFriendsStatusEnum.NOT_YOURSELF.status;
        }
        //3.不能添加自己
        QueryWrapper<MyFriends> wr = new QueryWrapper<>();
        wr.eq("my_user_id", myUserId);
        wr.eq("my_friend_user_id", users.getId());
        MyFriends myFriends = myFriendsMapper.selectOne(wr);
        if (myFriends != null) {
            return SearchFriendsStatusEnum.ALREADY_FRIENDS.status;
        }
        return SearchFriendsStatusEnum.SUCCESS.status;
    }

    //根据用户名查询用户信息
    @Override
    public Users queryUserInfoByUsername(String username) {
        QueryWrapper<Users> wr = new QueryWrapper<>();
        wr.eq("username", username);
        Users users = userMapper.selectOne(wr);
        return users;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    //添加好友请求记录
    @Override
    public void sendFriendRequest(String myUserId, String friendUsername) {
        Users friend = queryUserInfoByUsername(friendUsername);
        //查询好友请求记录表是否存在
        QueryWrapper<FriendsRequest> wr = new QueryWrapper<>();
        wr.eq("send_user_id",myUserId ).eq("accept_user_id", friend.getId());
        FriendsRequest friendsRequestlog = friendsRequestMapper.selectOne(wr);
        if (friendsRequestlog == null) {
            //还有记录不存在就添加好友请求记录
            String requestId = sid.nextShort();
            FriendsRequest friendsRequest = new FriendsRequest();
            friendsRequest.setId(requestId);
            friendsRequest.setSendUserId(myUserId);
            friendsRequest.setAcceptUserId(friend.getId());
            friendsRequest.setRequestDataTime(new Date());
            friendsRequestMapper.insert(friendsRequest);
        }
    }

    /**
     *查询好友请求列表(看谁向该用户发送了好友请求)
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<FriendsVo> queryFriendRequestList(String acceptUserId) {
        return userMapper.queryFriendRequestList(acceptUserId);
    }

    /**
     *删除好友请求记录
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteFriendRequest(String sendUserId, String acceptUserId) {
        QueryWrapper<FriendsRequest> wr = new QueryWrapper<>();
        wr.eq("send_user_id",sendUserId ).eq("accept_user_id", acceptUserId);
       friendsRequestMapper.delete(wr);
    }
    /**
     *通过好友请求记录
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void passFriendRequest(String sendUserId, String acceptUserId) {
        saveFriends(sendUserId,acceptUserId);
        saveFriends(acceptUserId,sendUserId);
        deleteFriendRequest(sendUserId,acceptUserId);

        Channel channel = UserChannelRel.get(sendUserId);
        if (channel != null) {
            //使用websocket主动推送消息到请求发起者，更新他的通讯录列表为最新
            DataContent dataContent = new DataContent();
            dataContent.setAction(MsgActionEnum.PULL_FRIEND.type);

            channel.writeAndFlush(new TextWebSocketFrame(JsonUtils.objectToJson(dataContent)));
        }
    }

    /**
     * 查找好友列表
     * @param myUserId
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<MyFriendsVo> queryMyFriends(String myUserId) {
        return userMapper.queryMyFriends(myUserId);
    }


    /**
     *保存聊天记录到数据库
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public String saveMsg(ChatMsg chatMsg) {
        com.xiaoxin_project.pojo.ChatMsg chatMsg1 = new com.xiaoxin_project.pojo.ChatMsg();
        String msgId = sid.nextShort();
        chatMsg1.setId(msgId);
        chatMsg1.setAcceptUserId(chatMsg.getReceiverId());
        chatMsg1.setSendUserId(chatMsg.getSenderId());
        chatMsg1.setCreateTime(new Date());
        chatMsg1.setSignFlag((MsgSignFlagEnum.unsign.type).toString());
        chatMsg1.setMsg(chatMsg.getMsg());

        chatMsgMapper.insert(chatMsg1);
        return msgId;
    }


    /**
     * 批量签收消息 更新消息为已签收
     * @param msgIdList
     */
    @Override
    public void updateMsgSigned(List<String> msgIdList) {
        UpdateWrapper<com.xiaoxin_project.pojo.ChatMsg> wr = new UpdateWrapper<>();
        wr.set("sign_flag",1).in("id",msgIdList);
        chatMsgMapper.update(null,wr);

    }

    /**
     *获取未签收的消息列表
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<com.xiaoxin_project.pojo.ChatMsg> getUnReadMsgList(String acceptUserId) {
        QueryWrapper<com.xiaoxin_project.pojo.ChatMsg> wr = new QueryWrapper<>();
        wr.eq("accept_user_id",acceptUserId).eq("sign_flag",0);
        List<com.xiaoxin_project.pojo.ChatMsg> chatMsgList = chatMsgMapper.selectList(wr);
        return chatMsgList;
    }


    @Transactional(propagation = Propagation.REQUIRED)
    public void saveFriends(String sendUserId,String acceptUserId){
        MyFriends myFriends = new MyFriends();
        myFriends.setId(sid.nextShort());
        myFriends.setFriendId(acceptUserId);
        myFriends.setMyUserId(sendUserId);
        myFriendsMapper.insert(myFriends);

    }


    @Override
    public Users sum() {
        Long aLong = userMapper.selectCount(null);
        QueryWrapper<Users> wr = new QueryWrapper<>();
        wr.eq("username", "zhangsan").eq("password", "333");
        Users users = userMapper.selectOne(wr);
        return users;
    }
}
